<?php

/**
 * @Author:      lyt
 * @DateTime:  2017-03-22 14:28:28
 * @Description: 用于洗车单的控制器
 */
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
class ScsCarWashOrderController extends BaseController
{
    /**
     * @Author:      lyt
     * @DateTime:  2017-03-22 14:28:46
     * @Description: 用于洗车单的详情展示
     */
    public function show(){
    	$validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
    	do{
    		if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=CarWashOrder::find(Input::get('order_id'));
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            $engineer_info=array();
            if($order->engineer_id != 0){
                $engineer_info=MaintenanceEngineers::where('id',$order->engineer_id)->where('type','shop')->select('id','name')->first();
            }    
            $order->product_name=Config::get('config.wash_product')[$order->producd_id];
            //订单支付记录
            $opr=CarWashOrderPayRecord::where('order_id',Input::get('order_id'))->select('pay_type','amount','create_type','create_by','pay_id','tran_no',"status")->first();
            $user_info=null;
            if($order->user_id){
                $u=Users::find($order->user_id);
                $user_info=array("name"=>$u->real_name,"phone"=>$u->phone,"user_type"=>$u->type);
            }
            $plate=array();
            $spo=ScanningPlatesOrders::where("order_id",$order->order_id)->first();
            if($spo){
                $slp=ScanningLicensePlates::find($spo->plate_id);
                $plate=array("plate_id"=>$slp->id,
                    "big_picture"=>Config::get('wentong.scanning_img_url').$slp->big_picture,
                    "small_picture"=>Config::get('wentong.scanning_img_url').$slp->small_picture);
            }
            $temp_arr=array("order_info"=>$order,"engineer_info"=>$engineer_info,"order_pay_record"=>$opr,"user_info"=>$user_info,"plate"=>$plate);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
    	}while(false);
    	Log::info("info", array("system" => "scs" ,"event" => "car_wash_show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
     /**
      * @Author:      lyt
      * @DateTime:  2017-03-22 15:58:20
      * @Description: 能选的项目
      */
    public function products(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }             
            $finally_arr=array();
            $close_array=Config::get('config.close_wash');
            foreach (Config::get('config.wash_product') as $key => $value) {
                if(isset($close_array)&&in_array($key, $close_array)){
                    continue;     
                }
                $ppi=ProductPackItem::where("pack_id",$key)->where("status",1)->where("type",2)->first();
                $spi=ServiceProductItem::find($ppi->item_id);
                //无聊的替换多城市定价 写死参数 类型
                $arr=Config::get('wash.wash_product')[$key];

                $p=null;
                $psc=PricingStrategyService::leftJoin("pricing_strategy","pricing_strategy.id","=","pricing_strategy_service.pricing_strategy_id")->where("pricing_strategy_service.serivee_id",$spi->id)->where("pricing_strategy.type",$arr["col_id"])->where("pricing_strategy.city_id",$sc_user->shop->city_id)->select("pricing_strategy.id")->first();
                if($psc){
                    $p=PricingStrategydetail::where("pricing_strategy_id",$psc->id)->where("column_type_id",$arr["col_val"])->first();
                }

                $finally_arr[]=array("pack_id"=>$key,"name"=>$value,"amount"=>isset($p)?$p->price:$spi->price);
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product"=>$finally_arr));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "products", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-08-03 10:35:54
     * @Description: 该车牌号和 服务能用的套餐卡
     * @link http://api.anhui.com/v1/scs/carwashorder/serviceCard?token=f5ca4cf3a2f3dd941d29b116a9c6a792&car_no=京FT3778&product_id=38
     */
    public function serviceCard(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
                'product_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }             
            $car_no=Input::get("car_no");
            $product_id=Input::get("product_id");

            //查找该用户 绑定了品类的用户id
            $scc=DB::table("service_card_car")->where("car_no",$car_no)->where("status",1)->select("user_id")->get();
            if(sizeof($scc)>0){
                $temp=array();
                foreach ($scc as $_scc) {
                    $temp[]=$_scc->user_id;
                }
                $scc=$temp;
            }
            /**
             * 选择合适的套餐卡产品 
             */
            $scdp=ServiceCardDetailPack::leftJoin("service_card_detail","service_card_detail.id","=","service_card_detail_pack.service_card_detail_id")->whereIn("service_card_detail.user_id",$scc)->where('service_card_detail.status',2)->where("service_card_detail.end_date",">=",date("Y-m-d",time()))->where("service_card_detail_pack.pack_id",$product_id)->where("service_card_detail_pack.curr_number",">",0)->orderBy("service_card_detail.created_at","asc")->select("service_card_detail_pack.*","service_card_detail.shop_id","service_card_detail.used_car_no","service_card_detail.user_id")->get();
            $finally_arr=array();      
            $remain_arr = [];     //存储套餐卡剩余次数数组
            foreach ($scdp as $_scdp) {
                $scb=ServiceCardBase::find($_scdp->service_card_base_id);
                $scbs=ServiceCardBaseShopUse::where("service_card_base_id",$scb->id)->where("shop_id",$sc_user->shop_id)->where("status",1)->first();//判断是否支持该门店
                if(is_null($scbs)||$scb->user_status==0){//改套餐卡不支持该门店 或者 该类型套餐卡停用
                    continue;
                }
                if($scb->limit_shop==1&&$_scdp->shop_id!=0&&$_scdp->shop_id!=$sc_user->shop_id){//说明套餐卡 限制购买门店使用
                    continue;
                } 
                $remain_arr[$_scdp->user_id] = isset($remain_arr[$_scdp->user_id])?($remain_arr[$_scdp->user_id]+$_scdp->curr_number):$_scdp->curr_number;
                if(!isset($finally_arr[$_scdp->user_id])){
                    $u=Users::where("id",$_scdp->user_id)->select("id","phone","real_name")->first();
                    $finally_arr[$_scdp->user_id]=$u;
                }
            }
            foreach ($finally_arr as &$v) {
                if(isset($remain_arr[$v->id])){
                    $v->total_curr_number = $remain_arr[$v->id];      //总的剩余次数
                }else{
                    $v->total_curr_number = 0;
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("user_arr"=>array_values($finally_arr)));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "serviceCard", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-5-21 上午10:50
     * @Description: 校验该车牌号是否绑定洗车套餐卡或者其他服务能用的套餐卡
     * @param string $token             用户token
     * @param string $car_no            车牌号
     * @param string $product_id        产品信息id串， 多个值用英文逗号隔开 例如 38,39
     * @link http://api.anhui.com/v1/scs/carwashorder/checkBindServiceCard?token=894ce517d59e31e6c21c42600fa45ac1&car_no=京FT3778&product_id=38,39
     */
    public function checkBindServiceCard(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
                'product_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }             
            $car_no = Input::get("car_no");
            $product_id = Input::get("product_id");
            $product_id_arr = explode(',', $product_id);    //产品信息id数组
            
            //查找该用户 绑定了品类的用户id
            $scc = DB::table("service_card_car")->where("car_no",$car_no)->where("status",1)->select("user_id")->get();
            if(sizeof($scc)>0){
                $temp=array();
                foreach ($scc as $_scc) {
                    $temp[]=$_scc->user_id;
                }
                $scc=$temp;
            }
            
            //选择合适的套餐卡产品 
            $scdp = ServiceCardDetailPack::leftJoin("service_card_detail","service_card_detail.id","=","service_card_detail_pack.service_card_detail_id")
                    ->leftJoin("service_card_base", "service_card_detail.service_card_base_id", "=", "service_card_base.id")
                    ->whereIn("service_card_detail.user_id",$scc)
                    ->where('service_card_detail.status',2)
                    ->where("service_card_detail.end_date",">=",date("Y-m-d",time()))
                    ->whereIn("service_card_detail_pack.pack_id",$product_id_arr)
                    ->where("service_card_detail_pack.curr_number",">",0)
                    ->where("service_card_base.user_status", 1)
                    ->orderBy("service_card_detail.created_at","asc")
                    ->select("service_card_detail_pack.*","service_card_detail.shop_id","service_card_detail.used_car_no","service_card_detail.user_id","service_card_base.name")
                    ->get();
            
            $base_id_arr = [];      //该门店所销售的套餐卡的id数组
            $bind_arr = [];         //存储是否绑定相应的套餐卡标识    0:未绑定;1:已绑定;
            foreach ($product_id_arr as $v) {
                $bind_arr[$v] = 0;
            }
            
            foreach ($scdp as $_scdp) {
                $base_id_arr[] = $_scdp->service_card_base_id;
                
                $scb = ServiceCardBase::find($_scdp->service_card_base_id);
                $scbs = ServiceCardBaseShopUse::where("service_card_base_id",$scb->id)
                        ->where("shop_id",$sc_user->shop_id)->where("status",1)->first();//判断是否支持该门店
                if(is_null($scbs)||$scb->user_status==0){//改套餐卡不支持该门店 或者 该类型套餐卡停用
                    continue;
                }
                if($scb->limit_shop==1&&$_scdp->shop_id!=0&&$_scdp->shop_id!=$sc_user->shop_id){//说明套餐卡 限制购买门店使用
                    continue;
                } 
                
                $bind_arr[$_scdp->pack_id] = 1;
            }
            
            //套餐卡详细信息
            $scd = ServiceCardDetail::leftJoin("service_card_base","service_card_detail.service_card_base_id","=","service_card_base.id")
                    ->whereIn("service_card_detail.user_id",$scc)
                    ->where('service_card_detail.status',2)
                    ->where("service_card_detail.end_date",">=",date("Y-m-d",time()))
                    ->where("service_card_base.user_status", 1)
                    ->orderBy("service_card_detail.created_at","asc")
                    ->select("service_card_detail.id","service_card_detail.service_card_base_id", 
                            "service_card_detail.shop_id","service_card_detail.used_car_no","service_card_detail.user_id",
                            "service_card_base.name")
                    ->get();
            $use_shop_info_arr = ServiceCardBaseShopUse::getShopUseInfo($base_id_arr);  //查询套餐卡的适用门店信息
            foreach ($scd as $v) {
                if(isset($use_shop_info_arr[$v->service_card_base_id])){
                    $v->shop_use = array_values($use_shop_info_arr[$v->service_card_base_id]);
                }else{
                    $v->shop_use = [];
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['list' => $bind_arr, 'service_card_info' => $scd]);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "serviceCard", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-03-22 15:06:16
     * @Description: 创建洗车单
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no'=>'required|max:20|alpha_dash',
                'product_id'=>'required',
                "pay_type"=>'required',
                'source' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }     
            $code=Input::get("code");
            $car_no=strtoupper(Input::get("car_no"));
            $product_id=Input::get("product_id");
            $pay_type=Input::get("pay_type");
            $user_id=Input::get("user_id");
            $card_no=Input::get("id_card_no");        
            $plate_id=Input::get("plate_id");     
            $source=Input::get("source");
            $reception_id=Input::get("reception_id"); 
            
            if(!isset(CarWashOrderPayRecord::$paytype[$pay_type])||!in_array($source,CarWashOrderPayRecord::$paytype_source[$pay_type])){
                $response = Lang::get("scs_error.order_pay_type_error_40096");
                break;
            }
            $ppi=ProductPackItem::where("pack_id",$product_id)->where("status",1)->where("type",2)->first();
            $spi=ServiceProductItem::find($ppi->item_id);
            //无聊的替换多城市定价 写死参数 类型
            $arr=Config::get('wash.wash_product')[$product_id];
            $psc=PricingStrategyService::leftJoin("pricing_strategy","pricing_strategy.id","=","pricing_strategy_service.pricing_strategy_id")->where("pricing_strategy_service.serivee_id",$spi->id)->where("pricing_strategy.type",$arr["col_id"])->where("pricing_strategy.city_id",$sc_user->shop->city_id)->select("pricing_strategy.id")->first();
            if($psc){
                $p=PricingStrategydetail::where("pricing_strategy_id",$psc->id)->where("column_type_id",$arr["col_val"])->first();
            }

            $order_amount=isset($p)?$p->price:$spi->price;//订单总价
            $pay_amount=$dis_amount=$weixindis_amount=0;
            $order_id = Common::createOrderId();
           
            $response=DB::transaction(function () use ($order_id,$pay_type,$sc_user,$car_no,$user_id,$product_id,$dis_amount,$order_amount,$code,$card_no,$plate_id,$source,$reception_id) {
                $service_card_detail_pack_id=0;
                if($pay_type==49||$pay_type==69||$pay_type==50){//说明是 洗车卡 支付 或者免费支付
                    $dis_amount=$order_amount;
                    if($pay_type==50){//如果是线上洗车卡支付
                        $scdp=ServiceCardDetailPack::leftJoin("service_card_detail","service_card_detail.id","=","service_card_detail_pack.service_card_detail_id")->where("service_card_detail.user_id",$user_id)->where('service_card_detail.status',2)->where("service_card_detail.end_date",">=",date("Y-m-d",time()))->where("service_card_detail_pack.pack_id",$product_id)->where("service_card_detail_pack.curr_number",">",0)->orderBy("service_card_detail.end_date","asc")->select("service_card_detail_pack.*","service_card_detail.shop_id","service_card_detail.used_car_no")->get();
                        $finally_arr=array();
                        foreach ($scdp as $_scdp) {
                            $scb=ServiceCardBase::find($_scdp->service_card_base_id);
                            $scbs=ServiceCardBaseShopUse::where("service_card_base_id",$scb->id)->where("shop_id",$sc_user->shop_id)->where("status",1)->first();//判断是否支持该门店
                            if(is_null($scbs)||$scb->user_status==0){//改套餐卡不支持该门店 或者 该类型套餐卡停用
                                continue;
                            }
                            if($scb->limit_shop==1&&$_scdp->shop_id!=0&&$_scdp->shop_id!=$sc_user->shop_id){//说明套餐卡 限制购买门店使用
                                continue;
                            }        
                            if($scb->limit_car==2){//说明套餐卡 限制购买用户车辆使用
                                $scc=DB::table("service_card_car")->where("user_id",$user_id)->where("car_no",$car_no)->where("status",1)->first();
                                if(is_null($scc)){//说明是 有绑定车辆
                                    continue;
                                }
                            } 
                            $finally_arr[]=array("status"=>1,"pack_id"=>$_scdp->pack_id,"id"=>$_scdp->id);
                            break;                            
                        }
                        if(sizeof($finally_arr)==0){//说明这个包都不满足这个订单
                            $response = Lang::get("scs_error.order_service_card_error_40133");
                            DB::rollback();
                            return $response;
                        }
                        $service_card_detail_pack_id=$finally_arr[0]["id"];
                    }
                }else{
                    if($code){
                        $coupon=Coupons::where('coupons.code',$code)->where("status",2)->first();
                        if(is_null($coupon)){
                            $response = Lang::get("scs_error.order_coupon_error_40071");
                            return $response;
                        }               
                        $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
                        if(!$cbi){ //优惠券基本信息不存在
                            $response = Lang::get("scs_error.order_coupon_error_40074");
                            return $response;
                        }
                        if($cbi->limit_order==1){ //如果是上门
                            return $response = Lang::get("scs_error.order_coupon_error_40092");
                        }
                        if($cbi->date_type==0){
                            if(strtotime($cbi->end_date.' 23:59:59') < time()||strtotime($cbi->begin_date.' 00:00:00')>time()){ //优惠券已过期
                                $response = Lang::get("scs_error.order_coupon_error_40075");
                                return $response;
                            }
                        }else{
                            if(strtotime($coupon->end_date.' 23:59:59') < time()){ //优惠券已过期
                                $response = Lang::get("scs_error.order_coupon_error_40075");
                                return $response;
                            }
                        }
                        if($cbi->limit_car==1){
                            if($coupon->used_car_no !=$car_no){ //优惠券已过期
                                $response = Lang::get("scs_error.order_coupon_error_40091");
                                return $response;
                            }
                        }

                        //判断限制类型           
                        if($cbi->limit_type==1){//如果是金额限制
                            if($cbi->limit_amount>$order_amount){
                                $response = Lang::get("scs_error.order_coupon_error_40129");
                                return $response;
                            }                
                        }
                        if($cbi->limit_type==2){//如果是服务限制
                            $limit_id=CouponPackLimit::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get();
                            $limit_arr=array();
                            foreach ($limit_id as $_li) {
                                $limit_arr[]=$_li->pack_id;
                            }
                            $t=array_diff($limit_arr,array($product_id));
                            if(sizeof($t)>0){//说明限制的服务订单中 又不存在的 
                                $response = Lang::get("scs_error.order_coupon_error_40127");
                                return $response;
                            }
                        }
                        //门店限制
                        $cp=CouponShop::where("coupon_base_id",$cbi->id)->where("shop_id",$sc_user->shop_id)->where("status",1)->first();
                        if(!$cp){ //该优惠券 不适合该门店
                            return $response = Lang::get("scs_error.order_coupon_error_40128");
                        }
                       

                        switch ($cbi->type) {
                            case 1://抵用券          
                                if($cbi->amount>$order_amount){//如果优惠金额大于订单今个 取消优惠券
                                    return $response = Lang::get("scs_error.order_coupon_error_40080");
                                }          
                                $dis_amount=$cbi->amount;
                                break;
                            case 2://服务抵用卷
                                $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                                if(is_null($pack_arr)){
                                    return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                }
                                if($pack_arr->pack_id!=$product_id){
                                    $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                    return $response;
                                } 
                                $dis_amount=$order_amount;//如果是订单折扣券
                                break;
                            case 3://实物抵用券
                                $response = Lang::get("scs_error.order_coupon_error_40071");
                                return $response;
                                break;
                            case 4://服务减免券
                                $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                                if(is_null($pack_arr)){
                                    return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                }
                                if($pack_arr->pack_id!=$product_id){
                                    $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                    return $response;
                                } 
                                $dis_amount=$cbi->amount;
                                break;
                            case 5://服务折扣券
                                $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->where("pack_id",$product_id)->first();
                                if(is_null($pack_arr)){
                                    return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                }
                                // if($cbi->pack_id!=$product_id){
                                //     $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                //     return $response;
                                // } 
                                $dis_amount=round($order_amount*(1-$cbi->discount));                           
                                break;
                        }
                        $coupon->status=4;//更改选中则优惠券状态为使用
                        $coupon->use_time=date('Y-m-d H:i:s',time());
                        $coupon->used_user_id=$coupon->received_user_id;
                        $coupon->save(); 
                        $coi=new CouponCarWashOrderInfo;
                        $coi->order_id=$order_id;
                        $coi->code=$coupon->code;
                        $coi->user_id=$coupon->used_user_id;
                        $coi->coupon_base_info_id=$coupon->coupon_base_info_id;
                        $coi->status=1;
                        $coi->coupon_id=$coupon->id;
                        $coi->save();                   
                    }  
                    // if($pay_type==3&&$source==1){ 当时微信支付价格优惠暂时取消
                    //     $dis_amount+=$order_amount*0.1;
                    //     if($dis_amount>$order_amount)
                    //         $dis_amount=$order_amount;
                    // }
                }  
                //添加用户 信息 如果选择用户 查看用户是否正常
                $user=null;
                if($user_id){
                    $user=Users::where("id",$user_id)->where("status",1)->first();
                    if(is_null($user)){
                        $response = Lang::get("scs_error.order_user_notexit_error_40097");
                        DB::rollback();
                        return $response;
                    }
                    //检查身份证后四位
                    if($user->type==1&&$pay_type!=50){//个人用户判断身份证
                        if(is_null($card_no)||strlen($card_no)!=4){
                            $response = Lang::get("scs_error.order_user_id_card_error_40098");
                            DB::rollback();
                            return $response;
                        }else{
                            if((substr($user->id_card,-4)!=$card_no)){
                                $response = Lang::get("scs_error.order_user_id_card_error_40098");
                                DB::rollback();
                                return $response;
                            }
                        }                    
                    }
                }else{
                    $user=Users::find(1000000000);
                }
                if($pay_type==6){//说明是挂账支付 检查 有没有选择用户或者用户是不是企业账户
                    if(is_null($user)||$user->type!=2){
                        $response = Lang::get("scs_error.order_user_notexit_error_40097");
                        DB::rollback();
                        return $response;
                    }
                    $c=Companys::find($user->id);
                    $check=Companys::accountDayStatus($c);
                    if($check["day_status"]=='逾期（禁止挂帐）'){
                      DB::rollback();
                      $response = Lang::get("scs_error.order_user_notpay_40111");
                      return $response;
                    }
                    $temp_pay_amount = $order_amount-$dis_amount;
                    $uad=UserAccountDeatails::where("user_id",$user->id)->where("acount_type",3)->first();
                    if(is_null($uad)||$uad->balance+$uad->credit<$temp_pay_amount){//说明账户不存在或者不足以支付
                        $response = Lang::get("scs_error.order_user_notpay_40039");
                        DB::rollback();
                        return $response;
                    }
                }
                if($pay_type==8){//说明余额支付
                    if(is_null($user)||$user->id==1000000000){
                        $response = Lang::get("scs_error.order_user_notexit_error_40097");
                        DB::rollback();
                        return $response;
                    }
                    $temp_pay_amount = $order_amount-$dis_amount;
                    $uad_balance=UserAccountDeatails::where("user_id",$user->id)->whereIn("acount_type",array(1,2))->sum("balance");
                    if($uad_balance<$temp_pay_amount){//说明账户不存在或者不足以支付                    
                        $response = Lang::get("scs_error.order_user_notpay_40039");
                        DB::rollback();
                        return $response;
                    }
                }
                $reception = SCUser::where('status',1)->find($reception_id);
                if (!$reception){
                    $response = Lang::get("scs_error.scs_user_isset_error_21019");
                    DB::rollback();
                    return $response;
                }
                $orders = new CarWashOrder();            
                $orders->order_id = $order_id;
                $orders->shop_id = $sc_user->shop_id;
                $orders->car_no = $car_no;
                $orders->phone = $user->phone;
                $orders->pay_type = $pay_type;
                $orders->begin_time = Common::currentTimeString();
                $orders->end_time =Common::currentTimeString();
                if($source==1){//说明不是微信 不是 pos支付 18s2修改为 途径为1 微信支付为线下暂时没有线上微信支付
                    $orders->status =1417;
                }else{
                    $orders->status =1411;
                }
                $orders->create_by = $sc_user->id;
                $orders->producd_id = $product_id;
                $orders->dis_amount = $dis_amount;
                $orders->amount = $order_amount;
                $orders->pay_amount = $order_amount-$dis_amount;
                $orders->user_id = $user->id;
                $orders->reception_id = $reception->id;
                $orders->reception_name = $reception->real_name;
                $orders->save();

                try{
                    if(isset($coupon)){
                        $push_couopn = CouponPush::Coupons($coupon->id,$coupon->coupon_base_info_id);
                        if(!is_null($push_couopn)){
                            $push_couopn->status = 2;
                            $push_couopn->updated_at = Common::currentTimeString();
                            $push_couopn->save();
                        }
                    }
                }catch (Exception $e){
                    DB::rollback();
                    Log::error("error", array("system" => "scs" ,"event" => "verification_coupons", 'input' =>Input::all() ,"exception" => $e));
                }

                $slp=ScanningLicensePlates::find($plate_id);
                if(isset($slp)&&$slp->collecting_shop==$sc_user->shop_id){//存在扫描件 并且一个门店
                    $spo=new ScanningPlatesOrders();
                    $spo->plate_id=$plate_id;
                    $spo->order_id=$order_id;
                    $spo->save();
                    $slp->used_plate=$car_no;
                    $slp->save();                    
                    $result = array(
                        'code' => 1,
                        'type' => 2,        
                        'shop_id' => $sc_user->shop_id,         
                        'order_id' => $order_id,
                        'plate_car_no' =>$slp->scanning_plate,
                        'plate_id' =>$slp->id,
                    ); 
                    RedisHelper::push($result,"anhui_wash_panel");
                }               
                $result = array(
                    'code' => 1,
                    'type' => 1,        
                    'shop_id' => $sc_user->shop_id,         
                    'order_id' => $order_id,
                    'plate_car_no' =>isset($slp)?$slp->scanning_plate:"",
                    'plate_id' =>isset($slp)?$slp->id:"",
                ); 
                RedisHelper::push($result,"anhui_wash_panel");
                
                $order_flows = new CarWashOrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status =1411;
                $order_flows->user_id = $sc_user->id;
                $order_flows->type = 'sc';
                $order_flows->save();
                if($source==1){//说明不是是微信 18s2修改为 途径为1 微信支付为线下暂时没有线上微信支付
                    $tr=CarWashOrder::pay($order_id,$pay_type,$sc_user->id,$service_card_detail_pack_id);
                    if($tr["code"]!=0){
                        DB::rollback();
                        return $tr;
                    }
                    $order_flows = new CarWashOrderFlows;
                    $order_flows->order_id = $order_id;
                    $order_flows->status =1417;
                    $order_flows->user_id = $sc_user->id;
                    $order_flows->type = 'sc';
                    $order_flows->save();
                    return $tr;
                }else if($source==2){//说明选择pos支付
                    $o_p=new CarWashOrderPayRecord;
                    $o_p->order_id=$order_id;
                    $o_p->pay_type=$pay_type;
                    $o_p->amount=$order_amount-$dis_amount;
                    $o_p->status=0;
                    $o_p->create_by=$sc_user->id;
                    $o_p->tran_no="";
                    $o_p->create_type="sc";
                    $o_p->save();   
                    //支付设备
                    $mpd=MaintenancePosDevice::where("id",Input::get("driver_id"))->where('shop_id',$orders->shop_id)->where('status',1)->first();
                    if(is_null($mpd)){
                      DB::rollback();
                      $response = Lang::get("scs_error.order_pay_driver_error_40116");
                      return $response;
                    }

                    // OrderPay::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
                    //调用智能pos 支付
                    $call_scan=($pay_type==20?1:0); 
                    $temp_pay_type=($pay_type==20?0:$pay_type);
                    $w=WposRecord::prepareOrder(3,$order_id,$o_p->id,$order_amount-$dis_amount,$user->id,$orders->shop_id,$mpd->device_no,$sc_user->id,$temp_pay_type,$call_scan);
                    if($w){
                      CarWashOrderPayRecord::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
                    }else{
                      CarWashOrderPayRecord::where("id",$o_p->id)->update(array("status"=>2,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
                    }
                    return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));  
                }else{//该判断暂时不走 或者将来要走 途径为 web
                    $o_p=new CarWashOrderPayRecord;
                    $o_p->order_id=$order_id;
                    $o_p->pay_type=3;
                    $o_p->amount=$order_amount-$dis_amount;
                    $o_p->status=0;
                    $o_p->create_by=$sc_user->id;
                    $o_p->tran_no="";
                    $o_p->create_type="sc";
                    $o_p->save();   
                    $order=CarWashOrder::find($order_id);
                    $wx = Config::get('wechat.CHEPIN');
                    $options = $wx['OPTION'];
                    $app = new Application($options);
                    $payment = $app->payment;
                    $attributes = [
                        'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
                        'body'             => '洗车',
                        'detail'           => '洗车服务费',
                        'out_trade_no'     => 'xc-'.$order->order_id,
                        'total_fee'        => $order->pay_amount, // 单位：分
                        'product_id'       => 'xiche',
                        'notify_url'       => Config::get('wechat.pay_note_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                        // 'openid'           => '当前用户的 openid', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                        // ...
                    ];
                    $weixin_order = new Order($attributes);
                    $result = $payment->prepare($weixin_order);
                    //记实录 微信支付信息  记录 支付记录
                    $wp=WeixinPayRecord::where("order_type",'xc')->where("order_id",$order->order_id)->first();
                    if(is_null($wp)){
                        $wp=new WeixinPayRecord;
                    } 
                    $wp->order_type="xc";
                    $wp->order_id=$order->order_id;  
                    $wp->amount=$order->pay_amount;   
                    if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                        $prepayId = $result->prepay_id;                              
                        $wp->pay_url=$result->code_url;                    
                        $wp->pay_id=$result->prepay_id;
                        $wp->status=0;                    
                        $wp->out_time=Common::num2DateTime(time()+2*60*60);
                        $wp->save();
                        CarWashOrderPayRecord::where("order_id",$order->order_id)->update(array("status"=>5));    
                        $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));                   
                    }else{
                        $wp->status=2;                    
                        $wp->save();
                        CarWashOrderPayRecord::where("order_id",$order->order_id)->update(array("status"=>2));
                        $response = Lang::get("scs_error.order_weixinpay_error_40089");
                    } 
                    return $response;
                }   
            });
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


   /**
    * @Author:      lyt
    * @DateTime:  2017-03-25 11:08:39
    * @Description: 检查优惠券 返回优惠券信息
    */
    public function check_code(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_id'=>'required',
                "pay_type"=>'required',
                "code"=>'required',
                "car_no"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }     
            $code=Input::get("code");
            $product_id=Input::get("product_id");
            $pay_type=Input::get("pay_type");
            $car_no=Input::get("car_no");
            $ppi=ProductPackItem::where("pack_id",$product_id)->where("status",1)->where("type",2)->first();
            $spi=ServiceProductItem::find($ppi->item_id);
             //无聊的替换多城市定价 写死参数 类型
            $arr=Config::get('wash.wash_product')[$product_id];
            $psc=PricingStrategyService::leftJoin("pricing_strategy","pricing_strategy.id","=","pricing_strategy_service.pricing_strategy_id")->where("pricing_strategy_service.serivee_id",$spi->id)->where("pricing_strategy.type",$arr["col_id"])->where("pricing_strategy.city_id",$sc_user->shop->city_id)->select("pricing_strategy.id")->first();
            if($psc){
                $p=PricingStrategydetail::where("pricing_strategy_id",$psc->id)->where("column_type_id",$arr["col_val"])->first();
            }
            $order_amount=isset($p)?$p->price:$spi->price;//订单总价
            // $order_amount=$spi->price;//订单总价
            $pay_amount=$dis_amount=$weixindis_amount=0;
            $order_id = Common::createOrderId();
            if($pay_type==49||$pay_type==69||$pay_type==50){//说明是 洗车卡 支付
                $dis_amount=$order_amount;
            }else{
                if($code){
                    $coupon=Coupons::where('coupons.code',$code)->where("status",2)->first();
                    if(is_null($coupon)){
                        $response = Lang::get("scs_error.order_coupon_error_40071");
                        return $response;
                    }               
                    $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
                    if(!$cbi){ //优惠券基本信息不存在
                        $response = Lang::get("scs_error.order_coupon_error_40074");
                        return $response;
                    }
                    if($cbi->limit_order==1){ //如果是上门
                        return $response = Lang::get("scs_error.order_coupon_error_40092");
                    }
                    if($cbi->date_type==0){
                        if(strtotime($cbi->end_date.' 23:59:59') < time()||strtotime($cbi->begin_date.' 00:00:00')>time()){ //优惠券已过期
                            $response = Lang::get("scs_error.order_coupon_error_40075");
                            return $response;
                        }
                    }else{
                        if(strtotime($coupon->end_date.' 23:59:59') < time()){ //优惠券已过期
                            $response = Lang::get("scs_error.order_coupon_error_40075");
                            return $response;
                        }
                    }
                    if($cbi->limit_car==1){
                        if($coupon->used_car_no !=$car_no){ //优惠券已过期
                            $response = Lang::get("scs_error.order_coupon_error_40091");
                            return $response;
                        }
                    }

                    //判断限制类型           
                    if($cbi->limit_type==1){//如果是金额限制
                        if($cbi->limit_amount>$order_amount){
                            $response = Lang::get("scs_error.order_coupon_error_40129");
                            return $response;
                        }                
                    }
                    if($cbi->limit_type==2){//如果是服务限制
                        $limit_id=CouponPackLimit::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get();
                        $limit_arr=array();
                        foreach ($limit_id as $_li) {
                            $limit_arr[]=$_li->pack_id;
                        }
                        $t=array_diff($limit_arr,array($product_id));
                        if(sizeof($t)>0){//说明限制的服务订单中 又不存在的 
                            $response = Lang::get("scs_error.order_coupon_error_40127");
                            return $response;
                        }
                    }
                    //门店限制
                    $cp=CouponShop::where("coupon_base_id",$cbi->id)->where("shop_id",$sc_user->shop_id)->where("status",1)->first();
                    if(!$cp){ //该优惠券 不适合该门店
                        return $response = Lang::get("scs_error.order_coupon_error_40128");
                    }
                   

                    // switch ($cbi->type) {
                    //     case 1://抵用券          
                    //         if($cbi->amount>$order_amount){//如果优惠金额大于订单今个 取消优惠券
                    //             return $response = Lang::get("scs_error.order_coupon_error_40080");
                    //         }          
                    //         $dis_amount=$cbi->amount;
                    //         break;
                    //     case 2://服务抵用卷
                    //         if($cbi->pack_id!=$product_id){
                    //             $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    //             return $response;
                    //         }       
                    //         $dis_amount=$order_amount;//如果是订单折扣券
                    //         break;
                    //     case 3://实物抵用券
                    //         $response = Lang::get("scs_error.order_coupon_error_40071");
                    //         return $response;
                    //         break;
                    //     case 4://服务减免券
                    //         if($cbi->pack_id!=$product_id){
                    //             $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    //             return $response;
                    //         } 
                    //         $dis_amount=$cbi->amount;
                    //         break;
                    //     case 5://服务折扣券
                    //         if($cbi->pack_id!=$product_id){
                    //             $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    //             return $response;
                    //         } 
                    //         $dis_amount=round($order_amount*(1-$cbi->discount));                           
                    //         break;
                    // }    

                    switch ($cbi->type) {
                        case 1://抵用券          
                            if($cbi->amount>$order_amount){//如果优惠金额大于订单今个 取消优惠券
                                return $response = Lang::get("scs_error.order_coupon_error_40080");
                            }          
                            $dis_amount=$cbi->amount;
                            break;
                        case 2://服务抵用卷
                            $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                            if(is_null($pack_arr)){
                                return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                            }
                            if($pack_arr->pack_id!=$product_id){
                                $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                return $response;
                            } 
                            $dis_amount=$order_amount;//如果是订单折扣券
                            break;
                        case 3://实物抵用券
                            $response = Lang::get("scs_error.order_coupon_error_40071");
                            return $response;
                            break;
                        case 4://服务减免券
                            $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                            if(is_null($pack_arr)){
                                return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                            }
                            if($pack_arr->pack_id!=$product_id){
                                $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                                return $response;
                            } 
                            $dis_amount=$cbi->amount;
                            break;
                        case 5://服务折扣券
                            $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->where("pack_id",$product_id)->first();
                            if(is_null($pack_arr)){
                                return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                            }
                            // if($cbi->pack_id!=$product_id){
                            //     $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                            //     return $response;
                            // } 
                            $dis_amount=round($order_amount*(1-$cbi->discount));                           
                            break;
                    }                               
                }  
                // if($pay_type==3&&$source==1){
                //     $dis_amount+=$order_amount*0.1;                    
                // }
                if($dis_amount>$order_amount)
                    $dis_amount=$order_amount;
            }                      

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_amount"=>$order_amount,"dis_amount"=>$dis_amount,"pay_amount"=>$order_amount-$dis_amount));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "check_code", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-03-28 09:19:04
     * @Description: 支付订单
     */
    public function weixinpay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=CarWashOrder::find(Input::get('order_id'));
            if(is_null($order)){//服务单才判断
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if($order->status!=1411||$order->pay_type!=3){
                $response = Lang::get("scs_error.order_weixinpay_error_40088");
                break;
            }
            //查看是否已经支付失败或者支付超市
            $wpr=WeixinPayRecord::where("order_type",'xc')->where("order_id",$order->order_id)->first();
            if($wpr){//如果存在支付记录
                if(strtotime($wpr->out_time)>time()){//如果还没过期  是重复支付
                    $response = Lang::get("scs_error.order_weixinpay_error_40090");
                    break;
                }
            }

            $wx = Config::get('wechat.CHEPIN');
            $options = $wx['OPTION'];

            $app = new Application($options);
            $payment = $app->payment;

            $attributes = [
                'trade_type'       => 'NATIVE', // JSAPI，NATIVE，APP...
                'body'             => '洗车',
                'detail'           => '洗车服务费',
                'out_trade_no'     => 'xc-'.$order->order_id,
                'total_fee'        => $order->pay_amount, // 单位：分
                'product_id'       => 'xiche',
                'notify_url'       => Config::get('wechat.pay_note_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                // 'openid'           => '当前用户的 openid', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $weixin_order = new Order($attributes);
            $result = $payment->prepare($weixin_order);
            Log::info($result);
            if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                //记实录 微信支付信息  记录 支付记录
                $wp=WeixinPayRecord::where("order_type",'xc')->where("order_id",$order->order_id)->first();
                if(is_null($wp)){
                    $wp=new WeixinPayRecord;
                }                
                $wp->pay_url=$result->code_url;
                $wp->order_type="xc";
                $wp->order_id=$order->order_id;
                $wp->pay_id=$result->prepay_id;
                $wp->status=0;
                $wp->amount=$order->pay_amount;
                $wp->out_time=Common::num2DateTime(time()+2*60*60);
                $wp->save();
                CarWashOrderPayRecord::where("order_id",$order->order_id)->update(array("status"=>5));    
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));                   
            }else{
                $response = Lang::get("scs_error.order_weixinpay_error_40089");
            } 
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
        
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-3-29 10:38:14
     * @Description: 订单取消
     */
    public function cancelOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok');
    
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $order=CarWashOrder::find(Input::get('order_id'));
            if(is_null($order)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            
            if($order->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            
            }
            
            $cwpr=CarWashOrderPayRecord::where('order_id',Input::get('order_id'))->first();

            // $wxp=WeiXinPay::where('order_id',Input::get('order_id'))->where('order_type','xc')->first();
            if($order->status != 1411 ||(isset($cwpr)&& in_array($cwpr->status, array(0,1,5,7)))){

                $response = Lang::get("scs_error.order_status_error_40025");
                break;
            }
    
            //取消订单
            $order->status=1410;
            $order->save();
            $order_flows = new CarWashOrderFlows;
            $order_flows->order_id = Input::get('order_id');
            $order_flows->status =1410;
            $order_flows->user_id = $sc_user->id;
            $order_flows->type = 'sc';
            $order_flows->save();

            //取消优惠券
             
            $coi=CouponCarWashOrderInfo::where("order_id",Input::get('order_id'))->first();
            if($coi){
                Coupons::where("id",$coi->coupon_id)->update(array("status"=>2));
                $coi->status=0;
                $coi->save();
            }    
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-04-27 09:34:59
     * @Description: 洗车单支付统计
     */
    public function total(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'start_time'=>'required',
                "end_time"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }     
            $start_time=Input::get("start_time")." 00:00:00";
            $end_time=Input::get("end_time")." 23:59:59";

            // $start_time=date("Y-m-d H:i:s",strtotime($start_time)+Config::get("config.report_time_diff"));
            // $end_time=date("Y-m-d H:i:s",strtotime($end_time)+Config::get("config.report_time_diff"));
            $amount=DB::select("SELECT
                cwopr.pay_type,
                sum(cwopr.amount) AS amount,
                count(1) as count
            FROM
                car_wash_order cwo
            LEFT JOIN car_wash_order_pay_record cwopr ON cwopr.order_id = cwo.order_id
            WHERE
                cwo.shop_id = ?
            AND cwo.`status` = 1417
            AND cwopr.`status` = 1
            AND cwo.pay_time BETWEEN ?
            AND ?
            GROUP BY
                cwopr.pay_type",array($sc_user->shop_id,$start_time,$end_time));
            $finally_arr=array();
            $total=array("amount"=>0,"count"=>0);
            foreach ($amount as $_a) {
                $finally_arr[$_a->pay_type]=$_a;
                $total["amount"]+=$_a->amount;
                $total["count"]+=$_a->count;
            }

            //计算退货的记录
            $re_amount=DB::select("SELECT
                rwr.pay_type,
                - sum(rwr.amount) AS amount,
                - count(1) as count
            FROM
                return_carwash_order roc
            LEFT JOIN return_washorder_record rwr ON rwr.return_washorder_id = roc.id
            LEFT JOIN car_wash_order cwo ON cwo.order_id = roc.order_id
            WHERE
                cwo.shop_id = ?
            AND roc.`status` = 1
            AND roc.implement_time BETWEEN ?
            AND ?
            GROUP BY
                rwr.pay_type",array($sc_user->shop_id,$start_time,$end_time));
            foreach ($re_amount as $_a) {
                if(isset($finally_arr[$_a->pay_type])){
                    $finally_arr[$_a->pay_type]->amount+=$_a->amount;
                    $finally_arr[$_a->pay_type]->count+=$_a->count;
                }else{
                    $finally_arr[$_a->pay_type]=$_a;
                }
                $total["amount"]+=$_a->amount;
                $total["count"]+=$_a->count;
            }
            $return_money = [];
            $record  =  AcountUserRechargeSpend::spendMoney($sc_user->shop_id,$start_time,$end_time); //充值消费记录
            $return_record = AcountUserRechargeSpendRe::returnSpendMoney($sc_user->shop_id,$start_time,$end_time);//充值退款记录

            if (!empty($record)) {
            foreach ($record as $value) {
                    $array = AcountUserRecharge::RechargeInfo($value->aurr_id); //根据充值记录，查找对应的门店名称和账户标虚
                    $key = $array['shop_id'].'_'.$array['acount_type'];
                    if(isset($return_money[$key])){
                        $return_money[$key]['amount'] = round($return_money[$key]['amount']+bcdiv($value->amount,100,6),2);
                    } else {
                        $return_money[$key] = $array;
                        $return_money[$key]['amount'] = round(bcdiv($value->amount,100,6),2);
                    }
            }
            }
            if (!empty($return_record)){
                foreach ($return_record as $value) {
                        $array = AcountUserRecharge::RechargeInfo($value->aurr_id); //根据充值记录，查找对应的门店名称和账户标虚
                        $key = $array['shop_id'].'_'.$array['acount_type'];
                        $return_money[$key]['amount'] = round($return_money[$key]['amount']-bcdiv($value->amount,100,6),2);
                }
            }
            $compan_fianly=array();
            $record = DB::select("SELECT u.id,u.real_name,sum(cwopr.amount) amount
                FROM
                    `car_wash_order` cwo
                LEFT JOIN car_wash_order_pay_record cwopr ON cwo.order_id = cwopr.order_id
                LEFT JOIN users u ON u.id = cwo.user_id
                WHERE cwo.shop_id=?
                AND cwo.`status` = 1417
                AND cwo.pay_time BETWEEN ?
                AND ?
                AND cwopr.pay_type = 6
                GROUP BY cwo.user_id",
                array($sc_user->shop_id,$start_time,$end_time));
            foreach ($record as $_a) {
                $compan_fianly[$_a->id]=$_a;
            }           

            $return_record=DB::select("SELECT u.id,u.real_name,-sum(rwr.amount) amount
                FROM return_carwash_order roc
                LEFT JOIN return_washorder_record rwr ON rwr.return_washorder_id = roc.id
                LEFT JOIN car_wash_order cwo ON cwo.order_id = roc.order_id
                LEFT JOIN users u ON u.id = cwo.user_id
                WHERE cwo.shop_id=?
                AND roc.`status` = 1
                AND roc.implement_time BETWEEN ?
                AND ?
                AND rwr.pay_type = 6
                GROUP BY cwo.user_id",
                array($sc_user->shop_id,$start_time,$end_time));
            foreach ($return_record as $_r) {
                if(isset($compan_fianly[$_r->id])){
                    $compan_fianly[$_r->id]->amount+=$_r->amount;
                }else{
                    $compan_fianly[$_r->id]=$_r;
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_amount"=>array_values($finally_arr),"total_amount"=>$total,"return_money"=> array_values($return_money),"company_amount"=>array_values($compan_fianly)));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "total", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-09-01 10:00:14
     * @Description: 订单面板
     */
    public function washOrderPanel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'start_time'=>'required',
                "end_time"=>'required',
            )
        );
    
        $response = array('code' => 0, 'msg' => 'ok');
    
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $start_time=Input::get("start_time")." 00:00:00";
            $end_time=Input::get("end_time")." 23:59:59";

            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $finally=array();
            $cwo=CarWashOrder::where("shop_id",$sc_user->shop_id)->where("shop_status",0)->where("created_at",">",$start_time)->where("created_at","<=",$end_time)->where("status",1411);
            if(Input::get("car_no")){
                $cwo=$cwo->where("car_no","like","%".Input::get("car_no")."%");
            }
            $cwo=$cwo->orderBy("created_at","desc")->select("order_id","car_no","pay_time","status","created_at")->get();
            foreach ($cwo as $_cwo) {
                $finally[]=$_cwo;
            }
            $cwo=CarWashOrder::where("shop_id",$sc_user->shop_id)->where("shop_status",0)->where("created_at",">",$start_time)->where("created_at","<=",$end_time)->where("status",1417);
            if(Input::get("car_no")){
                $cwo=$cwo->where("car_no","like","%".Input::get("car_no")."%");
            }
            $cwo=$cwo->orderBy("pay_time","desc")->select("order_id","car_no","pay_time","status","created_at")->get();
             foreach ($cwo as $_cwo) {
                $finally[]=$_cwo;
            }            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>count($finally),"order_arr"=>$finally));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "washOrderPanel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}